/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.alf.scriptrunner;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * ScriptRunner runs an script read since an input stream.
 *
 * @author jmnovelov
 */
public class ScriptRunner {

    private Connection connection;

    private CharProcessor processor;

    /**
     * Create an instance with the connection, input, and ';' as a delimiter
     *
     * @param connection current connection
     * @param input Script InputStream
     */
    public ScriptRunner(Connection connection, InputStream input) {
        this.connection = connection;
        processor = new CharProcessor(input);
    }

    /**
     * Create an instance with the conneciton, input and delimiter
     *
     * @param connection current connection
     * @param input Script InputStream
     * @param delimiter sentence delimiter
     */
    public ScriptRunner(Connection connection, InputStream input,
            String delimiter) {
        this.connection = connection;
        processor = new CharProcessor(input, delimiter);
    }

    /**
     * Executes the script
     *
     * @throws SQLException
     */
    public void execute() throws SQLException {
        for (String sqlInstruction : processor) {
            executeStmt(connection.createStatement(), sqlInstruction);
        }
    }

    private void executeStmt(Statement stmt, String sql) throws SQLException {
        try {
            stmt.execute(sql);
        } finally {
            stmt.close();
        }
    }
}
